// controllers/materialsListController.js
const MaterialsList = require('../models/materialsListModel');

const materialsListController = {
    // 获取所有材料
    async getAllMaterials(req, res) {
        try {
            const data = await MaterialsList.getAll();
            res.json({ success: true, data });
        } catch (error) {
            res.status(500).json({ success: false, message: error.message });
        }
    },

    // 获取单个材料
    async getMaterialById(req, res) {
        try {
            const data = await MaterialsList.getById(req.params.id);
            if (!data) return res.status(404).json({ success: false, message: '材料不存在' });
            res.json({ success: true, data });
        } catch (error) {
            res.status(500).json({ success: false, message: error.message });
        }
    },

    // 创建材料
    async createMaterial(req, res) {
        try {
            const id = await MaterialsList.create(req.body);
            res.json({ success: true, id });
        } catch (error) {
            res.status(500).json({ success: false, message: error.message });
        }
    },

    // 更新材料
    async updateMaterial(req, res) {
        try {
            const affected = await MaterialsList.update(req.params.id, req.body);
            if (affected === 0) return res.status(404).json({ success: false, message: '材料不存在或未更新' });
            res.json({ success: true, message: '更新成功' });
        } catch (error) {
            res.status(500).json({ success: false, message: error.message });
        }
    },

    // 删除材料（软删除）
    async deleteMaterial(req, res) {
        try {
            const affected = await MaterialsList.softDelete(req.params.id);
            if (affected === 0) return res.status(404).json({ success: false, message: '材料不存在' });
            res.json({ success: true, message: '删除成功' });
        } catch (error) {
            res.status(500).json({ success: false, message: error.message });
        }
    }
};

module.exports = materialsListController;
